<template>
  <div>
    <el-card style="margin-bottom:20px;max-width: 580px;">
      <div slot="header" class="clearfix">
        <span>修改账户密码</span>
      </div>

      <el-form ref="dialogForm" size="small" :model="dialogFormData" :rules="dialogFormRules" label-width="100px">

        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model.trim="dialogFormData.oldPassword" autocomplete="on" :type="passwordTypeOld" placeholder="请输入原密码" />
          <span class="show-pwd" @click="showPwdOld">
            <svg-icon :icon-class="passwordTypeOld === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model.trim="dialogFormData.newPassword" autocomplete="on" :type="passwordTypeNew" placeholder="请输入新密码" />
          <span class="show-pwd" @click="showPwdNew">
            <svg-icon :icon-class="passwordTypeNew === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model.trim="dialogFormData.confirmPassword" autocomplete="on" :type="passwordTypeConfirm" placeholder="请确认新密码" />
          <span class="show-pwd" @click="showPwdConfirm">
            <svg-icon :icon-class="passwordTypeConfirm === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

        <el-form-item>
          <el-button :loading="submitLoading" type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/store/user'
import { changePwd } from '@/api/system/user'
import JSEncrypt from 'jsencrypt'
import type { FormInstance, FormRules } from 'element-plus'

const userStore = useUserStore()
const dialogForm = ref<FormInstance>()
const submitLoading = ref(false)

const dialogFormData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordTypeOld = ref('password')
const passwordTypeNew = ref('password')
const passwordTypeConfirm = ref('password')

const publicKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbOYcY8HbDaNM9ooYXoc9s+R5o
R05ZL1BsVKadQBgOVH/kj7PQuD+ABEFVgB6rJNi287fRuZeZR+MCoG72H+AYsAhR
sEaB5SuI7gDEstXuTyjhx5bz0wUujbDK4VMgRfPO6MQo+A0c95OadDEvEQDG3KBQ
wLXapv+ZfsjG7NgdawIDAQAB
-----END PUBLIC KEY-----`

const confirmPass = (rule: any, value: string, callback: any) => {
  if (value) {
    if (dialogFormData.newPassword !== value) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  } else {
    callback(new Error('请再次输入新密码'))
  }
}

const dialogFormRules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: confirmPass, trigger: 'blur' }
  ]
})

const showPwdOld = () => {
  passwordTypeOld.value = passwordTypeOld.value === 'password' ? '' : 'password'
}

const showPwdNew = () => {
  passwordTypeNew.value = passwordTypeNew.value === 'password' ? '' : 'password'
}

const showPwdConfirm = () => {
  passwordTypeConfirm.value = passwordTypeConfirm.value === 'password' ? '' : 'password'
}

const submitForm = async () => {
  if (!dialogForm.value) return
  
  await dialogForm.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 密码RSA加密处理
        const encryptor = new JSEncrypt()
        // 设置公钥
        encryptor.setPublicKey(publicKey)
        // 加密密码
        const encryptedOldPassword = encryptor.encrypt(dialogFormData.oldPassword)
        const encryptedNewPassword = encryptor.encrypt(dialogFormData.newPassword)

        await changePwd({
          oldPassword: encryptedOldPassword,
          newPassword: encryptedNewPassword
        })

        ElMessage.success('修改成功')
        dialogFormData.oldPassword = ''
        dialogFormData.newPassword = ''
        dialogFormData.confirmPassword = ''
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const cancelForm = () => {
  dialogFormData.oldPassword = ''
  dialogFormData.newPassword = ''
  dialogFormData.confirmPassword = ''
  dialogForm.value?.resetFields()
}
</script>

<style scoped>
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 3px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }

</style>
